package com.example.automobile_positioning.fragment;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.example.automobile_positioning.R;
import com.example.automobile_positioning.activity.MainActivity;
import com.example.automobile_positioning.activity.PhotoShowActivity;
import com.example.automobile_positioning.activity.VideoShowActivity;
import com.example.automobile_positioning.util.ImageThumbnail;

public class Photofragment extends Fragment{
	
	private View view;
	private Button btn_photo;
	private Button show_photo;
	private Button show_video;
	private Activity activity = null;
	// 自定义的弹出框类
	private Button mPhoto;
	Uri imageUri=null;
	private View viewBg;
	List<Bitmap> bitmaps2 = new ArrayList<Bitmap>();
	ImageAdapter adapter;
	GridView gv;
	private Bitmap bitmap;
	private static final String FILE_PATH = Environment.getExternalStorageDirectory().getPath()+"/Photo";
	private static final String FILE_PATH1 = Environment.getExternalStorageDirectory().getPath()+"/Video";
	public void Photofragment() {
		// TODO Auto-generated constructor stub
	}
	
	public static Photofragment newInstance(){
		Photofragment photofragment=new Photofragment();
		Bundle bundle=new Bundle();
		photofragment.setArguments(bundle);
		return null;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		activity = getActivity();
		view = inflater.inflate(R.layout.activity_photo, container, false);
		btn_photo = (Button) view.findViewById(R.id.btn_photo);
		show_photo = (Button) view.findViewById(R.id.show_photo);
		show_video = (Button) view.findViewById(R.id.show_video);
		// 把文字控件添加监听，点击弹出自定义窗口
		btn_photo.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showpop();
			}
		});

		/**
		 * 查看指定照片
		 */
		show_photo.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(activity, PhotoShowActivity.class);
				startActivity(intent);  
			}
		});

		/**
		 * 查看指定视频
		 */
		show_video.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(activity, VideoShowActivity.class);
				startActivity(intent);  
			}
		});
		gv = (GridView) view.findViewById(R.id.gv);
		viewBg = view.findViewById(R.id.myView);// 初始化遮罩层
		adapter = new ImageAdapter(bitmaps2);
		gv.setAdapter(adapter);
		
		return view;
	}
	
	// Gridview的适配器
		private class ImageAdapter extends BaseAdapter {
			List<Bitmap> bitmaps = new ArrayList<Bitmap>();

			public ImageAdapter(List<Bitmap> bitmaps) {
				this.bitmaps = bitmaps;
			}

			@Override
			public int getCount() {
				return bitmaps.size();
			}

			@Override
			public Object getItem(int arg0) {
				return bitmaps.get(arg0);
			}

			@Override
			public long getItemId(int arg0) {
				return arg0;
			}

			@Override
			public View getView(int postion, View arg1, ViewGroup arg2) {
				ImageView iv = new ImageView(activity);
				iv.setImageBitmap(bitmaps.get(postion));
				return iv;
			}

		}
		/**
		 * 显示Pop窗口
		 * 
		 * @param context
		 */
		
		public void showpop() {
			View view = getActivity().getLayoutInflater().inflate(
					R.layout.popwindow_head_portrait, null);
			// 最后一个参数false 代表：不与其余布局发生交互， true代表：可以与其余布局发生交互事件
			final PopupWindow popWindow = new PopupWindow(view,
					LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, false) {
				// 重写popupWindow消失时事件
				@Override
				public void dismiss() {
					// 在pop消失之前，给咱们加的view设置背景渐变出场动画（Android3.0以上的开发环境，这里建议使用属性动画，那样很柔和，视觉效果更棒！）
					viewBg.startAnimation(AnimationUtils.loadAnimation(
							activity,
							R.anim.anim_bookshelf_folder_editer_exit));
					viewBg.setVisibility(View.GONE);
					super.dismiss();
				}
			};
			// 设置Pop入场动画效果
			popWindow.setAnimationStyle(R.style.bottom_PopWindowAnimation);
			// 设置Pop响应内部区域焦点
			popWindow.setFocusable(true);
			// 设置Pop响应外部区域焦点
			popWindow.setOutsideTouchable(true);
			// 设置PopupWindow弹出软键盘模式（此处为覆盖式）
			popWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
			popWindow
					.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
			// 响应返回键必须的语句
			popWindow.setBackgroundDrawable(new BitmapDrawable());
			// 在显示pop之前，给咱们加的view设置背景渐变入场动画（Android3.0以上的开发环境，这里建议使用属性动画，那样很柔和，视觉效果更棒！）
			viewBg.setVisibility(View.VISIBLE);
			viewBg.startAnimation(AnimationUtils.loadAnimation(activity,
					R.anim.anim_bookshelf_folder_editer_enter));
			// 依附的父布局自己设定，我这里为了方便，这样写的。
			popWindow.showAtLocation(viewBg, Gravity.BOTTOM, 0, 0);
			// popWindow内的控件点击监听
			OnClickListener clickListener = new OnClickListener() {
				@Override
				public void onClick(View v) {
					switch (v.getId()) {
					case R.id.popwindow_head_portrait_paizhao:
						// 根据文件地址创建文件
			             File filePic = new File(FILE_PATH);
			             if (filePic.exists()) {
			            	 filePic.delete();
			             }
			             
			            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						  imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"workupload.jpg"));  
						//指定照片保存路径（SD卡），workupload.jpg为一个临时文件，每次拍照后这个图片都会被替换  
						cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
						startActivityForResult(cameraIntent, 1);  
						
						break;
					case R.id.popwindow_head_portrait_luxiang:
						Intent intent = new Intent();
						intent.setAction("android.media.action.VIDEO_CAPTURE");
						intent.addCategory("android.intent.category.DEFAULT");
						File file = new File(FILE_PATH1);
						if (!file.exists()) {
							file.mkdirs();
						}
						File files = new File(file + "/video_"
								+ System.currentTimeMillis() + ".3gp");
						Uri uri = Uri.fromFile(files);
						// 限制时长
						intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
						startActivityForResult(intent, 0);
						Toast.makeText(activity, "录像。。", 0).show();
						break;
					}
					popWindow.dismiss();
				}
			};
			view.findViewById(R.id.popwindow_head_portrait_back)
					.setOnClickListener(clickListener);
			view.findViewById(R.id.popwindow_head_portrait_paizhao)
					.setOnClickListener(clickListener);
			view.findViewById(R.id.popwindow_head_portrait_luxiang)
					.setOnClickListener(clickListener);
		}
		
		// 保存在SD卡
		public void gridviews() {
			String sdStatus = Environment.getExternalStorageState();
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
				Log.v("TestFile", "SD card is not avaiable/writeable right now.");
				return;
			}
			FileOutputStream b = null;
			File file = new File(FILE_PATH);
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");// 获取当前时间，进一步转化为字符串
			String fileName = file +"/img_"+System.currentTimeMillis()+ ".jpg";
			if (!file.exists()) {
				file.mkdirs();// 创建文件夹
			}
			try {
				if (bitmap == null) {
					Toast.makeText(activity, "格式错误，请重新添加", 0).show();

				} else {
					b = new FileOutputStream(fileName);
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				try {
					if (b == null || bitmap == null) {
					} else {
						b.flush();
						b.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bitmap != null) {
				bitmap = ThumbnailUtils.extractThumbnail(bitmap, 220, 220);// 设置图片的缩略图
				bitmaps2.add(bitmap);
				gv.setVerticalSpacing(10);// 设置GridView的间距
				adapter.notifyDataSetChanged();
			}
		}
		
		@Override
		public void onActivityResult(int requestCode, int resultCode, Intent data) {
			// TODO Auto-generated method stub
			if (requestCode == 0) {
				Toast.makeText(activity, "录像成功,已保存在SD卡中", 0).show();
//				Uri selectedImage = data.getData();
//				String[] filePathColumn = { MediaStore.Images.Media.DATA };
//				Cursor cursor = getContentResolver().query(selectedImage,
//						filePathColumn, null, null, null);
//				cursor.moveToFirst();
	//
//				String path = cursor.getString(cursor
//						.getColumnIndex(MediaStore.Images.Media.DATA));
			}

			else if (resultCode == Activity.RESULT_OK) {
				 Bitmap camorabitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"/workupload.jpg"); 
				 if(null != camorabitmap ){
			         // 下面这两句是对图片按照一定的比例缩放，这样就可以完美地显示出来。
			         int scale = ImageThumbnail.reckonThumbnail(camorabitmap.getWidth(),camorabitmap.getHeight(), 500, 600);   
			         bitmap = ImageThumbnail.PicZoom(camorabitmap, camorabitmap.getWidth() / scale,camorabitmap.getHeight() / scale);  
			         //由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常  
			         camorabitmap.recycle();  
			        //将处理过的图片显示在界面上   
			         MainActivity.bitmapsPhoto.add(bitmap);
			         gridviews();   
			         new File(Environment.getExternalStorageDirectory()+"/workupload.jpg").delete(); // 删除临时保存图片
			       }
			
			}
			super.onActivityResult(requestCode, resultCode, data);
		}
}
